package io.github.wanggit.antrpc.gateway.starter;

import io.github.wanggit.antrpc.gateway.starter.containers.HttpUrlContainer;
import io.github.wanggit.antrpc.gateway.starter.containers.IHttpUrlContainer;
import io.github.wanggit.antrpc.gateway.starter.listeners.IListener;
import io.github.wanggit.antrpc.gateway.starter.listeners.RegisterNodeListener;
import io.github.wanggit.antrpc.gateway.starter.zk.IZkClient;
import io.github.wanggit.antrpc.gateway.starter.zk.ZkClient;
import io.github.wanggit.antrpc.gateway.starter.zk.ZkConfig;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GatewayContext implements IGatewayContext {

    private IZkClient zkClient;

    private IHttpUrlContainer httpUrlContainer;

    @Override
    public IZkClient getZkClient() {
        return zkClient;
    }

    @Override
    public IHttpUrlContainer getHttpUrlContainer() {
        return httpUrlContainer;
    }

    @Override
    public void init(ZkConfig zkConfig) {
        long start = System.currentTimeMillis();
        initZkClient(zkConfig);
        httpUrlContainer = new HttpUrlContainer();
        initRegisterNodeListener(zkClient, httpUrlContainer);
        if (log.isInfoEnabled()) {
            log.info(
                    "Gateway Context init finished... duration="
                            + (System.currentTimeMillis() - start)
                            + "ms");
        }
    }

    private void initRegisterNodeListener(IZkClient zkClient, IHttpUrlContainer httpUrlContainer) {
        IListener registerNodeListener = new RegisterNodeListener(zkClient, httpUrlContainer);
        registerNodeListener.listen();
    }

    private void initZkClient(ZkConfig zkConfig) {
        zkClient = new ZkClient(zkConfig);
    }
}
